
package com.epam.android.training.day10.task1;

import com.epam.android.training.day10.task1.Contacts.PersonalData;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

/**
 * Activity responsible for editing contacts and adding new into database.
 * 
 * @author Anton Novikov
 */
public class ContactEditor extends Activity {
  private static final String TAG = ContactEditor.class.getSimpleName();

  private static final String[] PROJECTION = {
      PersonalData._ID, PersonalData.FIRST_NAME, PersonalData.LAST_NAME, PersonalData.AGE
  };

  /** Called when the activity is starting. */
  @Override
  protected void onCreate(final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.contact_adder);
    final Intent intent = getIntent();

    if (intent == null) {
      unknownActionExit();
    }

    String action = intent.getAction();
    if (Intent.ACTION_INSERT.equals(action)) {
      addCreateButtonAction();

      addCancelButtonAction();
    } else if (Intent.ACTION_EDIT.equals(action)) {

      populateContactForm();

      addUpdateButtonAction();

      addCancelButtonAction();
    } else {
      unknownActionExit();
      return;
    }
  }

  /**
   * Adds action create to save button. Finishes activity after data is saved
   * into database.
   */
  private void addCreateButtonAction() {
    Button save = (Button) findViewById(R.id.save_button);
    save.setOnClickListener(new View.OnClickListener() {

      @Override
      public void onClick(View v) {
        EditText firstNameView = (EditText) findViewById(R.id.first_name);
        EditText lastNameView = (EditText) findViewById(R.id.last_name);
        EditText age = (EditText) findViewById(R.id.age);

        ContentValues values = new ContentValues();
        values.put(PersonalData.FIRST_NAME, firstNameView.getText().toString());
        values.put(PersonalData.LAST_NAME, lastNameView.getText().toString());
        try {
          String ageText = age.getText().toString();

          if (ageText != null && ageText.length() > 0) {
            values.put(PersonalData.AGE, Integer.parseInt(ageText));
          }
        } catch (NumberFormatException e) {
          Log.e(TAG, "Unable to convert age.", e);
        }
        getContentResolver().insert(PersonalData.CONTENT_URI, values);
        Toast.makeText(ContactEditor.this, R.string.success_add_message, Toast.LENGTH_SHORT).show();
        finish();
      }
    });
  }

  /**
   * Adds action update to save button. Finishes activity after data is saved
   * into database.
   */
  private void addUpdateButtonAction() {
    Button save = (Button) findViewById(R.id.save_button);
    save.setOnClickListener(new View.OnClickListener() {

      @Override
      public void onClick(View v) {
        EditText firstNameView = (EditText) findViewById(R.id.first_name);
        EditText lastNameView = (EditText) findViewById(R.id.last_name);
        EditText age = (EditText) findViewById(R.id.age);

        ContentValues values = new ContentValues();
        values.put(PersonalData.FIRST_NAME, firstNameView.getText().toString());
        values.put(PersonalData.LAST_NAME, lastNameView.getText().toString());
        values.put(PersonalData.AGE, Integer.parseInt(age.getText().toString()));

        Uri uri = getIntent().getData();
        String where = PersonalData._ID + "=" + uri.getPathSegments().get(1);

        getContentResolver().update(PersonalData.CONTENT_URI, values, where, null);
        Toast.makeText(ContactEditor.this, R.string.success_update_message, Toast.LENGTH_SHORT)
            .show();
        finish();
      }
    });
  }

  /**
   * Adds cancel button action. Finishes activity without saving data on the
   * form.
   */
  private void addCancelButtonAction() {
    Button cancel = (Button) findViewById(R.id.cancel_button);
    cancel.setOnClickListener(new View.OnClickListener() {

      @Override
      public void onClick(View v) {
        finish();
      }
    });
  }

  /**
   * Populates fields in the editor form with data from database.
   */
  private void populateContactForm() {
    Uri uri = getIntent().getData();

    Cursor resultSet = managedQuery(uri, PROJECTION, null, null, null);
    if (resultSet.getCount() > 0) {
      resultSet.moveToFirst();
      String firstName = resultSet.getString(resultSet.getColumnIndex(PersonalData.FIRST_NAME));
      String lastName = resultSet.getString(resultSet.getColumnIndex(PersonalData.LAST_NAME));
      Integer age = resultSet.getInt(resultSet.getColumnIndex(PersonalData.AGE));

      EditText firstNameView = (EditText) findViewById(R.id.first_name);
      EditText lastNameView = (EditText) findViewById(R.id.last_name);
      EditText ageView = (EditText) findViewById(R.id.age);

      firstNameView.setText(firstName);
      lastNameView.setText(lastName);
      ageView.setText(Integer.toString(age));
    } else {
      Toast.makeText(ContactEditor.this, R.string.contact_not_found_message, Toast.LENGTH_SHORT)
          .show();
      finish();
    }
  }

  /**
   * Logs the error message and finishes activity.
   */
  private void unknownActionExit() {
    // unknown action
    Log.e(TAG, "Unknown action, exiting");
    finish();
  }
}
